<template>
  <div class="update-name">
    <van-nav-bar title="修改昵称" left-text="取消" right-text="完成" @click-left="onClickLeft" @click-right="onConfirm" />
    <!-- 输入框 -->
    <div class="field-wrap">
      <van-field v-model.trim="localName" autosize type="textarea" maxlength="7" placeholder="请输入留言" show-word-limit />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user.js'
export default {
  name: 'updateName',

  data() {
    return {
      // 输入框内容
      localName: this.value
    }
  },

  props: {
    // 输入框内容
    value: {
      type: String,
      required: true
    }
  },

  methods: {
    // 取消逻辑操作
    onClickLeft() {
      // 通知父组件关闭弹出层
      this.$emit('close')
    },
    // 修改昵称操作
    async onConfirm() {
      try {
        if (this.localName) {
          await updateUserProfile({ name: this.localName })
          this.$toast.success('修改成功')
          this.$emit('close')
          // 通知父组件修改昵称
          this.$emit('input', this.localName)
        }
      } catch (error) {
        this.$toast.fail('修改昵称失败')
      }
    }
  }
}
</script>

<style lang="less" scope>
.field-wrap {
  padding: 10px;
}
</style>
